#include "pthread.h"
#include "stdio.h"
#include "unistd.h"
#include "sys/time.h"
#include "stdlib.h"

int sqr_fun(int num)
{
    int result = num * num;
    sleep(1);
    return result;
}

// 进程函数
void *sqr_thread(void *arg)
{
    int num = *(int *)arg;
    int *result = (int *)malloc(sizeof(int));
    *result = sqr_fun(num);
    
    // return result;
    // 结束线程，并返回返回值
    pthread_exit(result);
}

int main()
{
    int num[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    int sqr[5] = {0};
    pthread_t ptr[5]; // 定义线程
    // 定义时间
    struct timeval start, end;
    gettimeofday(&start, NULL);
    for (size_t i = 0; i < 5; i++)
    {
        pthread_create(ptr + i, NULL, sqr_thread, num + i);
    }

    for (size_t i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(ptr[i], &result);
        sqr[i] = *(int *)result;
    }
    
    gettimeofday(&end, NULL);

    printf("time: %ld\n", end.tv_sec - start.tv_sec);
    for (size_t i = 0; i < 5; i++)
    {
        sum += sqr[i];
    }
    printf("sum: %d\n",sum);

    return 0;
}